import React, { Component } from 'react';
import './player.scss';
import Progress from '../components/progress'
import { Link } from 'react-router-dom'
let $ = window.$
let musicDuration = null

class Player extends Component {
  constructor(props) {
    super(props)
    this.state = {
      progress: 0,
      volume: 0,
      isPlay: true
    }
  }

  changeProgressHandler (progress) {
    this.setState({
      progress: Math.floor(progress * 100)
    })
    $('#player').jPlayer(this.state.isPlay ? 'play' : 'pause', musicDuration * progress)
  }

  changeVolumnHandler (size) {
    this.setState({
      volume: Math.floor(size * 100)
    })
    $('#player').jPlayer('volume', size);
  }

  play () {
    $('#player').jPlayer(!this.state.isPlay ? 'play' : 'pause')
    this.setState({
      isPlay: !this.state.isPlay
    })
  }

  checkout (state) {
    this.setState({
      isPlay: true
    })
    this.props.changeMusic(state)
  }

  componentDidMount () {
    $('#player').bind($.jPlayer.event.timeupdate, (e) => {
      musicDuration = e.jPlayer.status.duration
      this.setState({
        volume: e.jPlayer.options.volume * 100,
        progress: e.jPlayer.status.currentPercentAbsolute,
        // leftTime: this.formatTime(musicDuration * e.jPlayer.status.currentPercentAbsolute / 100)
      })
    })
  }

  render() {
    return (
      <div className="player">
        <Link to="/list">播放列表</Link>
        <div className="title">{this.props.currenMusic.title}</div>
        <div className="singer">{this.props.currenMusic.artist}</div>
        <div className="volume-control">
          <div className="surplus">-0:00</div>
          <div className="volume">音量
            <div>
              <Progress progress={ this.state.volume } changeProgressHandler={this.changeVolumnHandler.bind(this)}></Progress>
            </div>
          </div>
        </div>
        <div className="progress-box">
          <Progress progress={ this.state.progress } changeProgressHandler={this.changeProgressHandler.bind(this)}></Progress>
        </div>
        <div className="music-control">
          <div className="prev" onClick={ this.checkout.bind(this, 'prev') }>上一曲</div>
          <div className="control" onClick={ this.play.bind(this) }>{`${this.state.isPlay ? '暂停' : '播放'}`}</div>
          <div className="next" onClick={ this.checkout.bind(this, 'next') }>下一曲</div>
        </div>
        <img src={this.props.currenMusic.cover} alt="404" className={ `cover${ this.state.isPlay ? ' play' : '' }` }/>
      </div>
    );
  }
}

export default Player;
